local taskName = "task_audio"

local MSG_MD = "moreData"   -- 播放缓存有空余
local MSG_PD = "playDone"   -- 播放完成所有数据
local MSG_NEW = "audioNew"  -- 播放新的歌曲

local musicDir = "/music/"

local playList = {}
local curPlay = 0
local prePlay = 0
local nextPlay = 1
local tFiles = 0

audio.on(0, function(id, event)
    --使用play来播放文件时只有播放完成回调
    local succ,stop,file_cnt = audio.getError(0)
    if not succ then
        if stop then
            log.info("用户停止播放")
        else
            log.info("第", file_cnt, "个文件解码失败")
        end
    end
    sysplus.sendMsg(taskName, MSG_PD)
end)


-- hw_i2c_id,sw_i2c_scl,sw_i2c_sda,spi_id,spi_res,spi_dc,spi_cs

-- 日志TAG, 非必须
local TAG = "main"

-- 初始化显示屏
log.info(TAG, "init ssd1306")

-- 初始化硬件i2c的ssd1306
u8g2.begin({ic = "ssd1306",direction = 0,mode="i2c_hw",i2c_id=0}) -- direction 可选0 90 180 270 -- direction 可选0 90 180 270
-- 初始化软件i2c的ssd1306
-- u8g2.begin({ic = "ssd1306",direction = 0,mode="i2c_sw", i2c_scl=sw_i2c_scl, i2c_sda=sw_i2c_sda})
-- 初始化硬件spi的ssd1306
-- u8g2.begin({ic = "ssd1306",direction = 0,mode="spi_hw_4pin",spi_id=spi_id,spi_res=spi_res,spi_dc=spi_dc,spi_cs=spi_cs})

u8g2.SetFontMode(1)
u8g2.ClearBuffer()
u8g2.SetFont(u8g2.font_opposansm8)
u8g2.DrawUTF8("U8g2+LuatOS", 32, 22)

if u8g2.font_opposansm8_chinese then
    u8g2.SetFont(u8g2.font_opposansm8_chinese)
elseif u8g2.font_opposansm10_chinese then
    u8g2.SetFont(u8g2.font_opposansm10_chinese)
end

u8g2.DrawUTF8("中文测试", 40, 38) -- 若中文不显示或乱码,代表所刷固件不带这个字号的字体数据, 可自行云编译一份. wiki.luatos.com 有文档.
u8g2.SendBuffer()


local function u8d2_disp()

    u8g2.ClearBuffer()
 
    u8g2.DrawUTF8((curPlay+1).."/"..(tFiles)..playList[curPlay], 0,10)
    if curPlay+1  < tFiles then
        u8g2.DrawUTF8((curPlay+2).."/"..(tFiles)..playList[curPlay+1], 0, 25)
    end
    if curPlay+2  < tFiles then
        u8g2.DrawUTF8((curPlay+3).."/"..(tFiles)..playList[curPlay+2], 0, 40)
    end
    
    u8g2.SendBuffer()

end

local function audio_task()

    spi_id,pin_cs = fatfs_spi_pin() 
    spi.setup(spi_id,nil,0,0,8,400*1000)
    gpio.setup(pin_cs, 1)
    fatfs.mount(fatfs.SPI,"/sd", spi_id, pin_cs, 12*1000*1000)

    -- 此为sdio方式,目前只101/103支持sdio,按需使用
    -- fatfs.mount(fatfs.SDIO,"/sd")
    local button = gpio.setup(22, 
    function() 
        audio.playStop(0)
        -- audio.play(0)
        -- sysplus.sendMsg(taskName, MSG_PD)
        -- if curPlay < tFiles then
        --     curPlay = curPlay + 1
        -- else
        --     curPlay = 0
        -- end
    end, gpio.PULLUP,gpio.FALLING)



    local data, err = fatfs.getfree("/sd")
    if data then
        log.info("fatfs", "getfree", json.encode(data))
    else
        log.info("fatfs", "err", err)
    end
    if data then
        log.info("fatfs", "getfree", json.encode(data))
        local dir_nums, dir_info = fatfs.lsdir(musicDir)
        for k,v in pairs(dir_info) do
            if k:find(".mp3") or k:find(".MP3") or k:find(".wav") or k:find(".WAV") then
                log.info("找到",tFiles..k)
                playList[tFiles] = k
                tFiles = tFiles + 1
                
            end
        end
   

    local result
    --Air780E开发板配套
    i2s.setup(0, 0, 0, 0, 0, i2s.MODE_MSB)
    audio.config(0, 25, 1, 6, 200)
    gpio.setup(24, 0)
    gpio.setup(23, 0)
    gpio.setup(27, 0)
    gpio.setup(2, 0)
    audio.vol(0, 10)
    while true do
        log.info("开始播放")
        u8d2_disp()
        log.info((curPlay+1).."/"..(tFiles)..playList[curPlay])
        result = audio.play(0, "/sd".. musicDir .. playList[curPlay])
        if result then
        --等待音频通道的回调消息，或者切换歌曲的消息
            while true do
                msg = sysplus.waitMsg(taskName, nil)
                if type(msg) == 'table' then
                    if msg[1] == MSG_PD then
                        log.info("播放结束")
                        
                        if (curPlay + 1) < tFiles then
                            curPlay = curPlay + 1
                        else
                            curPlay = 0
                        end
                        break
                    end
                else
                    log.error(type(msg), msg)
                end
            end
        else
            log.debug("解码失败!")
            sys.wait(1000)
        end
        if not audio.isEnd(0) then
            log.info("手动关闭")
            audio.playStop(0)
        end
        log.info(rtos.meminfo("sys"))
        log.info(rtos.meminfo("lua"))
        sys.wait(1000)
    end
    sysplus.taskDel(taskName)
end
end

sysplus.taskInitEx(audio_task, taskName, task_cb)